<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-15
 * Time: 下午2:15
 */

namespace appapi\modules\v0\controllers;


use common\components\tools\ArrayHelper;
use common\members\wodrow\tools\Tools;
use common\models\db\Area;
use common\models\db\EquipmentAppVersion;
use common\models\db\EquipmentOperateLog;
use common\models\db\Smms;
use common\models\db\Tag;
use common\rewrite\deepziyu\yii_fast_api\Controller;
use GDText\Box;
use GDText\Color;
use yii\web\Response;

class PublicController extends Controller
{
    /**
     * public测试
     * @desc get/post
     * @param string $a moren xxx
     * @return array
     * @return string x test
     * @return string y y
     */
    public function actionIndex($a = 'xxx')
    {
        $r = [
            'a' => $a,
            'x' => 1,
            'y' => 1,
        ];
        return $r;
    }

    /**
     * public测试图片上传
     * @desc post
     * @return array
     */
    public function actionTestImageUpload()
    {
        var_dump($_FILES);
        var_dump($_REQUEST);
        exit;
    }

    /**
     * 生产环境模拟认证测试
     * @desc get/post
     * @param string $uuid
     * @param string $app_version_id
     * @param string $token
     * @param string $key
     * @return array
     */
    public function actionProdTestSend($uuid, $app_version_id, $token, $key)
    {
        $timestamp = Yii_BT_TIME;
        $nonce = $timestamp . rand(1000, 9999);
        $params = [
            'uuid' => $uuid,
            'app_version_id' => $app_version_id,
            'token' => $token,
            'timestamp' => $timestamp,
            'nonce' => $nonce,
            'key' => $key,
        ];
        ksort($params);
        $arr = [];
        foreach ($params as $k => $v) {
            $arr[] = $k . "=" . $v;
        }
        $str = ArrayHelper::arr2str($arr, "&");
        $sign = md5($str);
        $params['sign'] = $sign;
        return $params;
    }

    /**
     * 微信公众号服务器配置接入
     */
    public function actionWeiXinTokenConfig()
    {
        //1. 将timestamp , nonce , token 按照字典排序
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = "wyii2";
        $signature = $_GET['signature'];
        $array = array($timestamp,$nonce,$token);
        sort($array);

        //2.将排序后的三个参数拼接后用sha1加密
        $tmpstr = implode('',$array);
        $tmpstr = sha1($tmpstr);

        //3. 将加密后的字符串与 signature 进行对比, 判断该请求是否来自微信
        if($tmpstr == $signature)
        {
            echo $_GET['echostr'];
            exit;
        }
    }

    /**
     * 获取设备操作类型键值对
     * @desc get/post
     * @return array
     * @return object equipment_operate_types 设备操作类型
     */
    public function actionGetEquipmentOperateType()
    {
        $r['equipment_operate_types'] = EquipmentOperateLog::getEquipmentOperateType();
        return $r;
    }

    /**
     * 获取所有app版本列表
     * @desc get/post
     * @return array list 所有app版本
     */
    public function actionGetEquipmentAppVersionList()
    {
        $r['list'] = EquipmentAppVersion::find()->asArray()->all();
        return $r;
    }

    /**
     * 获取子地区列表
     * @desc get/post
     * @param int $area_id 地区id
     * @return array list 子地区
     */
    public function actionGetChildArea($area_id = Area::CHINA_AREA_ROOT)
    {
        $areas = Area::find()->where(['fid' => $area_id])->asArray()->all();
        $r['list'] = $areas;
        return $r;
    }

    /**
     * 获取标签
     * @desc get/post 后台使用
     * @param string $query tag名
     * @return array 获取到的标签
     */
    public function actionTagList($query = '')
    {
        $this->onlyDataOut = true;
        $models = Tag::findAllByName($query);
        $items = [];

        foreach ($models as $model) {
            $items[] = ['name' => $model->name];
        }
        // We know we can use ContentNegotiator filter
        // this way is easier to show you here :)
        \Yii::$app->response->format = Response::FORMAT_JSON;

        return $items;
    }

    /**
     * wangeditor上传图片后台配置
     * desc wangeditor使用
     * @return array | string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function actionUploadPicsForWangeditor()
    {
        $this->onlyDataOut = true;
        /*if (count($_FILES)>9){
            return "error|服务器端错误";
        }*/
        foreach ($_FILES as $k => $v) {
            $size = $v['size'];
            if ($size > 5 * 1024 * 1024) {
                echo $size / 1024 / 1024;
                exit;
            }
        }
        $data = [];
        foreach ($_FILES as $k => $v) {
            $tmp_name = $v['tmp_name'];
            $tmp_path = \Yii::getAlias('@storage_root/tmp/' . $v['name']);
            file_put_contents($tmp_path, file_get_contents($tmp_name));
            $s = new Smms();
            $s->uploadLocalFile($tmp_path);
            $data[] = $s->url;
        }
        $resp = [
            'errno' => 0,
            'data' => $data,
            'files' => $_FILES,
            'req' => $_REQUEST,
        ];
        return $resp;
    }

    /**
     * 生成文字头像
     * @desc get 由浏览器打开直接为图片
     * @param int $w 图片宽度
     * @param int $h 图片高度
     * @param string $text 文字
     * @param string $backgroundColor 背景色
     * @param string $fontColor 文字颜色
     * @param int $fontSize 文字大小
     */
    public function actionTextAvatarImage($w = 200, $h = 200, $text = 'text', $backgroundColor = '000000', $fontColor = 'ffffff', $fontSize = 80)
    {
        $this->resp_format = Response::FORMAT_RAW;
        $this->onlyDataOut = true;
        $im = imagecreatetruecolor($w, $h);
        $bk_color_arr = \common\members\wodrow\tools\Color::hex2rgb($backgroundColor, 'arr');
        $backgroundColor = imagecolorallocate($im, $bk_color_arr['red'], $bk_color_arr['green'], $bk_color_arr['blue']);
        imagefill($im, 0, 0, $backgroundColor);
        $box = new Box($im);
        $box->setFontFace(\Yii::getAlias('@data/fonts/fzlsft.ttf')); // http://www.dafont.com/franchise.font
        $f_color_arr = \common\members\wodrow\tools\Color::hex2rgb($fontColor, 'arr');
        $box->setFontColor(new Color($f_color_arr['red'], $f_color_arr['green'], $f_color_arr['blue']));
        $box->setTextShadow(new Color(0, 0, 0, 50), 0, 0);
        $box->setFontSize($fontSize);
        $box->setBox(0, 0, $w, $h);
        $box->setTextAlign('center', 'center');
        $box->draw($text);
        header("Content-type: image/png");
        imagepng($im);
    }
}